package com.manastudent.tools;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.ui.Messages;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.stream.Collectors;

public class FormatSelectionAction extends AnAction {
    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        final Editor editor = e.getData(CommonDataKeys.EDITOR);
        if (editor == null) return;

        String selectedText = editor.getSelectionModel().getSelectedText();
        if (selectedText == null || selectedText.trim().isEmpty()) {
            Messages.showInfoMessage("请先选择非空白文本", "提示");
            return;
        }

        try {
            // 处理选中的文本
            String result = Arrays.stream(selectedText.split("[,\\n]"))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(s -> "'" + s + "'")
                    .collect(Collectors.joining(","));

            // 替换选中内容
            WriteCommandAction.runWriteCommandAction(editor.getProject(), () -> {
                int start = editor.getSelectionModel().getSelectionStart();
                int end = editor.getSelectionModel().getSelectionEnd();
                editor.getDocument().replaceString(start, end, result);
            });

        } catch (Exception ex) {
            Messages.showErrorDialog("处理失败: " + ex.getMessage(), "错误");
        }
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
        // 只在有文本选中时显示菜单项
        Editor editor = e.getData(CommonDataKeys.EDITOR);
        boolean hasSelection = editor != null && editor.getSelectionModel().hasSelection();
        e.getPresentation().setEnabledAndVisible(hasSelection);
    }
}